package com.kvn.interceptor;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.util.JdbcConstants;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by wangzhiyuan on 2018/6/6
 */
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class MyBatisInterceptor implements Interceptor {
    @Resource
    private SqlReseter sqlReseter;


    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 1. SQL解析
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0]; // statement
        Object paramObject = args[1]; // dao中传递的参数
        BoundSql boundSql = ms.getBoundSql(paramObject);
        final String SQL_ORIGIN = boundSql.getSql(); // sqlMap中的原SQL语句
        List<SQLStatement> sqlStatements = getSQLStatement(SQL_ORIGIN);
        List<SqlParserResult> sqlParserResults = new SqlParser(SQL_ORIGIN, paramObject, ms, boundSql, sqlStatements).parse();

        // 2. SQL改写
        Set<String> newSqlSet = sqlReseter.reset(sqlParserResults, sqlStatements);

        // 3. SQL执行
        return new InvocationProxy(invocation, newSqlSet).proceed();
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties properties) {

    }

    private static final Map<String/* SQL */, List<SQLStatement>> SQLStatementCacheMap = new ConcurrentHashMap<>();
    public static List<SQLStatement> getSQLStatement(String sql){
        List<SQLStatement> sqlStatements = SQLStatementCacheMap.get(sql);
        if (sqlStatements == null) {
            synchronized (sql) {
                sqlStatements = SQLStatementCacheMap.get(sql);
                if (sqlStatements == null) {
                    sqlStatements = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL);
                    SQLStatementCacheMap.put(sql, sqlStatements);
                }
            }
        }
        return SQLStatementCacheMap.get(sql);
    }
}
